import sys
import pygame
from pygame.sprite import Group
from love import Love
	
def run_game():
	# 初始化游戏，设置和屏幕对象
	pygame.init()
	screen = pygame.display.set_mode((750, 495))
	screen_rect = screen.get_rect()
	pygame.display.set_caption("I love you")

	# 设置背景色(RGB，0～255，红/绿/蓝)
	bg_color = (245, 245, 245)

	# 创建爱心编组和爱心群
	loves = Group()
	love = Love()
	number_x = int(750 / (2 * love.rect.width))
	number_y = int(495 / (2 * love.rect.height)+1)	
	for x in range(number_x):
		for y in range(number_y):
			love = Love()
			love.rect.x = love.rect.width + 2 * love.rect.width * x
			love.rect.y = -love.rect.height + 2 * love.rect.height * y
			love.y = love.rect.y
			loves.add(love)
	
	# 开始游戏的主循环
	while True:
		
		# 监视键盘和鼠标事件
		for event in pygame.event.get():
			if event.type == pygame.QUIT:
				sys.exit()
			elif event.type == pygame.KEYDOWN:
				if event.key == pygame.K_q:
					sys.exit()
		
		flag = False
		# 检查是否有爱心到达底端，若有，则消失
		for love in loves.sprites():
			if love.rect.top >= screen_rect.bottom:
				loves.remove(love)
				flag = True
				
		#如果有消失，新落下一些爱心
		if flag:
			for x in range(number_x):
				love = Love()
				love.rect.x = love.rect.width + 2 * love.rect.width * x
				love.rect.y = -love.rect.height
				love.y = love.rect.y
				loves.add(love)
						
		# 更新屏幕上的图像，并切换到新屏幕
		screen.fill(bg_color)	
		loves.update()
		loves.draw(screen)
		pygame.display.flip()

run_game()

